<template>
  <div class="validate-input-container pb-3">
    <input
      class="form-control"
      :class="{'is-valid': inputRef.error}"
      v-model="inputRef.val"
      @blur="validateInput"
    >
    <span class="invalid-feeback" v-if="inputRef.error">{{inputRef.message}}</span>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, PropType } from 'vue'

const regEmail = /[a-zA-Z0-9]+([-_.][A-Za-zd]+)*@([a-zA-Z0-9]+[-.])+[A-Za-zd]{2,5}$/

interface RuleProp {
  type: 'required' | 'email'
  message: string
}

export type RuleProps = PropType[]

export default defineComponent({
  name: 'ValidateInput',
  props: {
    rules: {
      type: Array as PropType<RuleProps>
    }
  },
  setup(props: PropType) {
    const inputRef = reactive({
      val: '',
      error: false,
      message: ''
    })
    const validateInput = () => {
      if (props.rules) {
        const allPassed = props.rules.every((rule: RuleProp) => {
          let passed = true
          inputRef.message = rule.message
          switch (rule.type) {
            case 'required':
              passed = !inputRef.val.trim().length
              break
            case 'email':
              passed = regEmail.test(inputRef.val)
              break
            default:
              break
          }
          return passed
        })
        inputRef.error = !allPassed
      }
    }
    return {
      inputRef,
      validateInput
    }
  }
})
</script>
